package com.alkaid.proxy;


import com.alkaid.entity.Impl.PersonImpl;
import com.alkaid.entity.Person;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TimingProxy {


    public static Person createProxy(PersonImpl person) {


        return (Person) Proxy.newProxyInstance(
                // 当前类的加载器
                TimingProxy.class.getClassLoader(),
                // 被生成代理的代理目标
                new Class[]{Person.class},
                // 代理目标行为
                new InvocationHandler() {
                    /**
                     *
                     * @param proxy 被代理的对象
                     *
                     * @param method 代理方法
                     *
                     * @param args 被代理调用的方法参数
                     *
                     * @return
                     * @throws Throwable
                     */
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        long startTime = System.currentTimeMillis();
                        Object result = method.invoke(person, args);
                        long endTime = System.currentTimeMillis();
                        System.out.println("Method " + method.getName() + " took " + (endTime - startTime) + " ms");
                        return result;
                    }
                }

        );
    }

}
